package main

import (
	"go-scripts/models"
	"fmt"
	"runtime/debug"
	"os"
	"gopkg.in/mgo.v2/bson"
	//"time"
	//"io"
	"time"
	//"strings"
	"github.com/Luxurioust/excelize"
)

func main()  {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("panic")
			fmt.Println(err)
			debug.PrintStack()
			os.Exit(0)
		}
	}()
	model, err := models.GetModel()
	if err != nil {
		panic(err.Error())
	}
	userDao, err := model.GetModelCollection("User")
	feedbackDao, err := model.GetModelCollection("Feedback")
	if err != nil {
		panic(err.Error())
	}
	feedbackAll := []*models.Feedback{}
	feedbacks := []map[string]interface{}{}
	pipline := []bson.M{
		{
			"$match": bson.M{
				"createdAt": bson.M{
					"$gt": time.Date(2017, 6, 15, 0, 0 , 0, 0, time.UTC),
				},
			},
		},
		{
			"$group": bson.M{
				"_id": "$mobile",
				"content": bson.M{
					"$push": "$content",
				},
			},
		},
		{
			"$project": bson.M{
				"mobile": "$_id",
				"content": 1,
			},
		},
	}
	feedbackDao.Pipe(pipline).All(&feedbacks)
	fmt.Println(feedbacks[0]["mobile"])
	fmt.Println(feedbacks[0]["content"])
	id2FeedbackMap := make(map[string]interface{})
	var mobiles []string
	for _, v := range feedbacks {
		mobile := v["mobile"].(string)
		id2FeedbackMap[mobile] = v
		mobiles = append(mobiles, mobile)
	}
	users := []*models.User{}
	userDao.Find(bson.M{
		"mobile": bson.M{
			"$in": mobiles,
		},
	}).Select(bson.M{
		"mobile": 1,
		"createdAt": 1,
	}).All(&users)

	//fmt.Println(len(users))
	//fmt.Println(len(feedbacks))
	//file, err := os.Create("feedback.csv")
	if err != nil {
		panic(err.Error())
	}
	//fmt.Println(len(feedbacks))
	feedbackDao.Find(bson.M{
		"createdAt": bson.M{
			"$gt": time.Date(2017, 6, 15, 0, 0 , 0, 0, time.UTC),
		},
	}).Select(bson.M{
		"content": 1,
		"mobile": 1,
	}).All(&feedbackAll)
	//for _, v := range feedbackAll {
	//	//fmt.Println(id2FeedbackMap[v.Mobile])
	//	content := strings.Replace(v.Content, "\n", "", -1)
	//	io.WriteString(file,  v.Mobile + "\t" + content + "\n")
	//}
	//file, err := os.Open("抽奖清单")
	chou, err := excelize.OpenFile("抽奖清单.xlsx")
	if err != nil {
		panic(err.Error())
	}

	datas := chou.GetRows("Sheet1")
	phones := []string{}
	for _, rows := range datas {
		for _, row := range rows {
			phones = append(phones, row)
		}
	}
	userInfos := []*models.User{}
	userDao.Find(bson.M{
		"mobile": bson.M{
			"$in": phones,
		},
	}).Select(bson.M{
		"mobile": 1,
		"createdAt": 1,
	}).All(&userInfos)
	file := excelize.CreateFile()
	if err != nil {
		panic(err.Error())
	}
	sheet := "Sheet1"
	file.NewSheet(1, sheet)
	for i, user := range userInfos {
		phoneCell := "A"
		createCell := "B"
		file.SetCellStr(sheet, fmt.Sprintf("%s%d", phoneCell, i + 1), user.Mobile)
		file.SetCellStr(sheet, fmt.Sprintf("%s%d", createCell, i + 1), user.CreatedAt.Format("2006-01-02 15:03:04"))
	}
	file.WriteTo("user.xlsx")
}